#!/usr/local/bin/ruby
# 
#  TAXONFINDER 2
#
#  taxonFinder.rb
#    Ruby version of TaxonFinder, which uses a morpho-syntactic approach for names identification and discovery
#  
#  2007-11-05
#  
#  Indra Neil Sarkar, PhD
#  MBLWHOI Library
#  Marine Biological Laboratory
#  7 MBL Street
#  Woods Hole, MA 02543 USA
#  sarkar@mbl.edu
#  
#  
#  Copyright 2007 Marine Biological Laboratory. All rights reserved.
# 

# ====================================================
# = identify taxonomic names within a phrase of text =
# ====================================================
def identifyTaxonomicNames(phrase,rankScoreHash)
  
  # split words into array, using space as a delimiter
  wordArray = phrase.split(/\s+/)
  
  wordArray.each do |word|
    puts word
    
    # consider all possible stem lengths
    for stemLength in 1..(word.size)
      
      # split the word into candidate Stem and Suffix morphemes
      word[/.{#{stemLength}}(.*)/]
      wordSuffix = $1.gsub(/\W/,"")

      puts wordSuffix
      
      if rankScoreHash.has_key? wordSuffix
        puts "=====> #{word} is a taxonomic word candidate"
        
        
        
        break
      end
    end
    
  end
     
end


# ====================
# = phrase tokenizer =
# ====================
def phraseTokenizer(inputText,rankScoreHash)
  
  puts inputText
  
  phraseArray = inputText.split(/(?<=\w{2})\.\s?/)
  
  phraseArray.each do |phrase|
    phrase = phrase.gsub(/\s+/,"\s")
    puts "---> #{phrase}"
    identifyTaxonomicNames(phrase,rankScoreHash)
  end
end


# ====================
# = load rank scores =
# ====================
def loadRankScores(rankScoreFileName)
  
  puts "*** load rankScores"
  
  # instantiate rankScoreHash [nameValue][rankName] = score
  rankScoreHash = Hash.new { |nameValue, rankName| nameValue[rankName] = {} }

  # load the rank scores form the file
  lineCount = 0
  File.open(rankScoreFileName).each do |rankScoreLine|
    lineCount = lineCount + 1
    next if lineCount == 1
    
    nameValue, overallScore, phylumScore, classScore, orderScore, familyScore, genusScore, speciesScore = rankScoreLine.chomp.split(/\|/)
    
    rankScoreHash["#{nameValue}"]["overall"] = overallScore
    rankScoreHash["#{nameValue}"]["phylum"]  = phylumScore
    rankScoreHash["#{nameValue}"]["class"]   = classScore
    rankScoreHash["#{nameValue}"]["order"]   = orderScore
    rankScoreHash["#{nameValue}"]["family"]  = familyScore
    rankScoreHash["#{nameValue}"]["genus"]   = genusScore
    rankScoreHash["#{nameValue}"]["species"] = speciesScore
  end
  
  return rankScoreHash
end


rankScoreHash = Hash.new { |rankName, nameValue| rankName[nameValue] = {} }

rankScoreHash = loadRankScores("../morphanalysis/suffixRankScores.txt")

inputText = "Escherichia coli,    f E. coli. Second sentence here contains another organism name: Drosophila melanogaster. Yet, one must wonder about Otitis media"
phraseTokenizer(inputText, rankScoreHash)


# identifyTaxonomicNames(phrase)
